// 企业认证状态管理
class CertificationManager {
  constructor() {
    this.status = null
    this.lastCheck = null
    this.checkInterval = 5 * 60 * 1000 // 5分钟缓存
    this.storageKey = 'enterprise_certification_status'
    
    // 尝试从本地存储恢复状态
    this.loadFromStorage()
  }

  // 从本地存储加载状态
  loadFromStorage() {
    try {
      const stored = localStorage.getItem(this.storageKey)
      if (stored) {
        const data = JSON.parse(stored)
        this.status = data.status
        this.lastCheck = data.lastCheck
      }
    } catch (error) {
      console.warn('从本地存储加载认证状态失败:', error)
    }
  }

  // 保存状态到本地存储
  saveToStorage() {
    try {
      const data = {
        status: this.status,
        lastCheck: this.lastCheck
      }
      localStorage.setItem(this.storageKey, JSON.stringify(data))
    } catch (error) {
      console.warn('保存认证状态到本地存储失败:', error)
    }
  }

  // 获取认证状态
  async getStatus() {
    const now = Date.now()
    
    // 如果缓存未过期，直接返回
    if (this.status && this.lastCheck && (now - this.lastCheck) < this.checkInterval) {
      return this.status
    }

    try {
      // 检查是否有token
      const token = localStorage.getItem('access_token')
      if (!token) {
        throw new Error('没有有效的认证token')
      }

      // 获取企业用户ID
      const userId = localStorage.getItem('user_id')
      if (!userId) {
        throw new Error('没有有效的用户ID')
      }

      const response = await fetch(`/api/api/v1/enterprise/certification/status/${userId}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      
      if (response.ok) {
        const data = await response.json()
        // 转换API响应格式为内部格式
        const statusData = {
          status: data.status,
          companyName: data.companyName,
          message: this.getStatusMessage(data.status)
        }
        this.status = statusData
        this.lastCheck = now
        this.saveToStorage()
        return statusData
      } else if (response.status === 404) {
        // 404错误，说明用户未提交认证
        const statusData = {
          status: 'unsubmitted',
          companyName: '',
          message: '未提交认证申请'
        }
        this.status = statusData
        this.lastCheck = now
        this.saveToStorage()
        return statusData
      } else if (response.status === 401) {
        // 401错误，说明token无效或过期
        throw new Error('认证token无效')
      } else {
        throw new Error(`API请求失败: ${response.status}`)
      }
    } catch (error) {
      console.warn('获取企业认证状态失败:', error.message)
      // 返回默认状态，让用户进入认证流程
      const defaultStatus = {
        status: 'unsubmitted',
        message: '未提交认证申请',
        error: error.message
      }
      this.status = defaultStatus
      this.lastCheck = now
      this.saveToStorage()
      return defaultStatus
    }
  }

  // 检查是否已认证
  async isCertified() {
    try {
      const status = await this.getStatus()
      return status.status === 'approved'
    } catch (error) {
      return false
    }
  }

  // 检查是否正在审核
  async isPending() {
    try {
      const status = await this.getStatus()
      return status.status === 'pending_review'
    } catch (error) {
      return false
    }
  }

  // 检查是否被拒绝
  async isRejected() {
    try {
      const status = await this.getStatus()
      return status.status === 'rejected'
    } catch (error) {
      return false
    }
  }

  // 检查是否未提交
  async isUnsubmitted() {
    try {
      const status = await this.getStatus()
      return status.status === 'unsubmitted'
    } catch (error) {
      return false
    }
  }

  // 清除缓存
  clearCache() {
    this.status = null
    this.lastCheck = null
    // 同时清除本地存储
    try {
      localStorage.removeItem(this.storageKey)
    } catch (error) {
      console.warn('清除本地存储失败:', error)
    }
  }

  // 更新状态（提交认证后调用）
  updateStatus(newStatus) {
    this.status = newStatus
    this.lastCheck = Date.now()
    this.saveToStorage()
  }



  // 根据状态获取消息
  getStatusMessage(status) {
    switch (status) {
      case 'pending_review':
        return '等待审核'
      case 'approved':
        return '已通过认证'
      case 'rejected':
        return '认证被拒绝'
      case 'unsubmitted':
        return '未提交认证申请'
      default:
        return '未知状态'
    }
  }
}

export const certificationManager = new CertificationManager() 